import { login } from '@/services/api';
import { Button, Card, Checkbox, Form, Input, Space, message } from 'antd';
import React from 'react';
import styles from './login.less';

export interface ILoginProps {
  [key: string]: any;
}

type FieldType = {
  name?: string;
  password?: string;
};

const Login: React.FC<ILoginProps> = () => {
  const [loginForm] = Form.useForm();
  const onFinish = async (values: FieldType) => {
    const res = await login(values);
    if (res.data.code && res.data.code === '901') {
      return message.warning(res.data.message || '登录失败');
    }
    if (res.status !== 200) {
      return message.error('登录失败');
    }
    localStorage.setItem('vehicle_token', res.data.token);
    setTimeout(() => {
      window.location.replace('/home')
    }, 1000);
    message.success('登录成功');
  };

  return (
    <div className={styles.container}>
      <Card style={{ width: 500 }}>
        <div className={styles.title}>登&nbsp;&nbsp;&nbsp;&nbsp;录</div>
        <Form
          name="basic"
          form={loginForm}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          // initialValues={formVal}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="用户名"
            name="name"
            rules={[{ required: true, message: '请输入你的用户名!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item<FieldType>
            valuePropName="checked"
            wrapperCol={{ offset: 4, span: 16 }}
          >
            <Checkbox checked>记住我</Checkbox>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 14, span: 16 }}>
            <Space>
              <Button htmlType="button" onClick={() => loginForm.resetFields()}>
                重置
              </Button>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
